extends RigidBody2D

var initial_position: Vector2
var max_velocity = 800.0
var bounce_factor = 0.8
var air_resistance = 0.98  # 空气阻力系数
var ground_friction = 0.95  # 地面摩擦力系数

func _ready():
	initial_position = global_position
	
	# 设置球的物理属性
	gravity_scale = 0.5
	linear_damp = 0.05  # 减少线性阻尼，让惯性更明显
	angular_damp = 0.1
	
	# 连接碰撞信号
	body_entered.connect(_on_body_entered)

func _physics_process(delta):
	# 限制最大速度
	if linear_velocity.length() > max_velocity:
		linear_velocity = linear_velocity.normalized() * max_velocity
	
	# 应用空气阻力（更真实的物理模拟）
	apply_air_resistance()
	
	# 根据是否在地面上应用不同的阻力
	if global_position.y > 700:  # 假设地面y坐标约为700
		apply_ground_friction()

	position = position.clamp(Vector2.ZERO, get_viewport_rect().size)
	
func apply_air_resistance():
	# 空气阻力与速度的平方成正比
	var speed = linear_velocity.length()
	if speed > 0:
		var resistance_force = -linear_velocity.normalized() * (speed * speed * 0.0001)
		apply_central_force(resistance_force)

func apply_ground_friction():
	# 地面摩擦力
	if linear_velocity.length() > 10:  # 只有速度足够大时才应用摩擦力
		var friction_force = -linear_velocity.normalized() * 50.0
		apply_central_force(friction_force)

func _on_body_entered(body):
	if body.has_method("hit_ball"):
		# 玩家击球
		body.hit_ball(self)
	elif body.name == "Net":
		# 球撞到网
		bounce_off_net()
	elif body.name == "Court":
		# 球撞到场地边界
		bounce_off_court()

func bounce_off_net():
	# 球撞网时的反弹
	var normal = Vector2(-1, 0) if global_position.x > 640 else Vector2(1, 0)
	linear_velocity = linear_velocity.bounce(normal) * bounce_factor
	
	# 添加一些随机性，模拟真实羽毛球的反弹
	var random_variation = randf_range(0.9, 1.1)
	linear_velocity *= random_variation

func bounce_off_court():
	# 球撞场地边界时的反弹
	var normal = Vector2.ZERO
	
	if global_position.x <= 200:
		normal = Vector2(1, 0)
	elif global_position.x >= 1080:
		normal = Vector2(-1, 0)
	elif global_position.y <= 100:
		normal = Vector2(0, 1)
	elif global_position.y >= 620:
		normal = Vector2(0, -1)
	
	if normal != Vector2.ZERO:
		linear_velocity = linear_velocity.bounce(normal) * bounce_factor
		
		# 添加一些随机性
		var random_variation = randf_range(0.85, 1.15)
		linear_velocity *= random_variation

func reset():
	global_position = initial_position
	linear_velocity = Vector2.ZERO
	angular_velocity = 0

# 添加一些视觉效果
func _on_ball_hit():
	# 当球被击中时的视觉效果
	var tween = create_tween()
	tween.tween_property($Sprite2D, "scale", Vector2(1.2, 1.2), 0.1)
	tween.tween_property($Sprite2D, "scale", Vector2(1.0, 1.0), 0.1) 
